package com.example.movie.ui.user

import android.app.DatePickerDialog
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.text.Selection
import android.text.Spannable
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.SimpleAdapter
import android.widget.Toast
import android.widget.Toolbar
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.example.movie.R
import com.example.movie.common.constants.AppConstants
import com.example.movie.common.constants.RequestCode
import com.example.movie.common.model.RequestResult
import com.example.movie.data.user.factory.UserInfoViewModelFactory
import com.example.movie.data.user.login.model.LoggedInUser
import com.example.movie.data.user.model.UserInfoViewModel
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import kotlinx.android.synthetic.main.layout_user_info_edit.*
import okhttp3.MediaType
import okhttp3.RequestBody
import java.io.ByteArrayOutputStream

private const val ATTRIBUTE = "ATTRIBUTE"
private const val VALUE = "VALUE"
private const val ACTION = "ICON"

class UserInfoEditActivity : AppCompatActivity() {

    private val userInfoViewModel: UserInfoViewModel by viewModels(factoryProducer = { UserInfoViewModelFactory() })

    private val attributes = arrayOf("昵称", "性别", "生日", "生活状态", "从事行业", "兴趣爱好", "个性签名")

    private var hasSwitchHeadImage:Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_user_info_edit)
        setObservers()
        initView()
    }

    private fun initView() {
        toolbar.setNavigationOnClickListener {
            onBackPressed()
        }

        toolbar.setOnMenuItemClickListener(object : Toolbar.OnMenuItemClickListener,
            androidx.appcompat.widget.Toolbar.OnMenuItemClickListener {

            override fun onMenuItemClick(item: MenuItem?): Boolean {
                when (item?.itemId) {
                    R.id.action_save -> {
                        userInfoViewModel.userInfo.value?.success?.let {
                            if (hasSwitchHeadImage) {
                                head_image.isDrawingCacheEnabled = true
                                head_image.buildDrawingCache(true)
                                val headPortrait = RequestBody.create(
                                    MediaType.parse("image/png"),
                                    bitmap2Bytes(head_image.drawingCache)
                                )
                                userInfoViewModel.updateUser(
                                    it,
                                    headPortrait
                                )

                                //上传完一次头像立马重置头像选择标志，以免上传重复头像
                                hasSwitchHeadImage = false

                            } else {
                                userInfoViewModel.updateUser(
                                    it,
                                    null
                                )
                            }
                        }

                    }
                }
                return true
            }

        })

        change_head_portrait.setOnClickListener {
            with(Intent()) {
                this.type = "image/**"
                this.putExtra("crop", true);// 设置Intent中的view是可以裁剪的
                // 设置宽高比
                this.putExtra("aspectX", 1);
                this.putExtra("aspectY", 1);
                // 设置裁剪图片的宽高
                this.putExtra("outputX", 360);
                this.putExtra("outputY", 360);
                this.putExtra("outputFormat", "JPEG");// 图片格式
                // 设置是否返回数据
                this.putExtra("return-data", true);
                startActivityForResult(this, RequestCode.SWITCH_HEAD_IMAGE)
            }

        }

        user_info_list.onItemClickListener =
            AdapterView.OnItemClickListener { adapterView: AdapterView<*>, view1: View, position: Int, l: Long ->
                val userInfo = userInfoViewModel.userInfo.value?.success

                when (position) {
                    UserInfo.NICK_NAME.ordinal -> {
                        val builder = QMUIDialog.EditTextDialogBuilder(this)
                        builder.setTitle("修改昵称")
                            .setDefaultText(userInfo?.userName)
                            .addAction("取消") { _dialog: QMUIDialog, _: Int ->
                                _dialog.dismiss()
                            }
                            .addAction("确定") { _dialog: QMUIDialog, _: Int ->
                                userInfo?.userName = builder.editText.text.toString()
                                userInfoViewModel.userInfo.value = RequestResult(success = userInfo)
                                _dialog.dismiss()
                            }
                            .show()

                        setEdiTextFocusPoint(builder)
                    }
                    UserInfo.GENDER.ordinal -> {
                        val builder = QMUIDialog.MenuDialogBuilder(this)
                        builder.setTitle("请选择性别")
                            .addItem("男") { dialogInterface: DialogInterface, i: Int ->
                                userInfo?.sex = "男"
                                userInfoViewModel.userInfo.value = RequestResult(success = userInfo)
                                dialogInterface.dismiss()
                            }
                            .addItem("女") { dialogInterface: DialogInterface, i: Int ->
                                userInfo?.sex = "女"
                                userInfoViewModel.userInfo.value = RequestResult(success = userInfo)
                                dialogInterface.dismiss()
                            }
                            .show()

                    }
                    UserInfo.BIRTHDAY.ordinal -> {

                        val date = userInfo?.birthDay?.split("-")

                        val datePickerDialog = DatePickerDialog(
                            this,
                            DatePickerDialog.THEME_DEVICE_DEFAULT_DARK,
                            { _, year, month, dayOfMonth ->
                                val birthDay = mutableListOf(
                                    year,
                                    month,
                                    dayOfMonth
                                ).joinToString(separator = "-")

                                Log.d("", "onActivityCreated: $birthDay")
                                userInfo?.birthDay = birthDay
                                userInfoViewModel.userInfo.value = RequestResult(success = userInfo)
                            },
                            (if (null == date?.get(0)) -1 else date[0].toInt()),
                            (if (null == date?.get(0)) -1 else date[1].toInt()),
                            (if (null == date?.get(0)) -1 else date[2].toInt())
                        )

                        datePickerDialog.show()
                    }
                    UserInfo.LIFE_STATUS.ordinal -> {
                        val builder = QMUIDialog.EditTextDialogBuilder(this)
                        builder.setTitle("修改生活状态")
                            .setDefaultText(userInfo?.marry)
                            .addAction("取消") { _dialog: QMUIDialog, _: Int ->
                                _dialog.dismiss()
                            }
                            .addAction("确定") { _dialog: QMUIDialog, _: Int ->
                                userInfo?.marry = builder.editText.text.toString()
                                userInfoViewModel.userInfo.value = RequestResult(success = userInfo)
                                _dialog.dismiss()
                            }
                            .show()

                        setEdiTextFocusPoint(builder)

                    }
                    UserInfo.JOB.ordinal -> {
                        val builder = QMUIDialog.EditTextDialogBuilder(this)
                        builder.setTitle("修改从事行业")
                            .setDefaultText(userInfo?.major)
                            .addAction("取消") { _dialog: QMUIDialog, _: Int ->
                                _dialog.dismiss()
                            }
                            .addAction("确定") { _dialog: QMUIDialog, _: Int ->
                                Log.d("", "onActivityCreated:${builder.editText.text} ")
                                userInfo?.major = builder.editText.text.toString()
                                userInfoViewModel.userInfo.value = RequestResult(success = userInfo)
                                _dialog.dismiss()
                            }
                            .show()

                        setEdiTextFocusPoint(builder)

                    }
                    UserInfo.HOBBY.ordinal -> {
                        val builder = QMUIDialog.EditTextDialogBuilder(this)
                        builder.setTitle("修改兴趣爱好")
                            .setDefaultText(userInfo?.hobbit)
                            .addAction("取消") { _dialog: QMUIDialog, _: Int ->
                                _dialog.dismiss()
                            }
                            .addAction("确定") { _dialog: QMUIDialog, _: Int ->
                                userInfo?.hobbit = builder.editText.text.toString()
                                userInfoViewModel.userInfo.value = RequestResult(success = userInfo)
                                _dialog.dismiss()
                            }
                            .show()

                        setEdiTextFocusPoint(builder)

                    }
                    UserInfo.SIGN.ordinal -> {
                        val builder = QMUIDialog.EditTextDialogBuilder(this)
                        builder.setTitle("修改签名")
                            .setDefaultText(userInfo?.sign)
                            .addAction("取消") { _dialog: QMUIDialog, _: Int ->
                                _dialog.dismiss()
                            }
                            .addAction("确定") { _dialog: QMUIDialog, _: Int ->
                                userInfo?.sign = builder.editText.text.toString()
                                userInfoViewModel.userInfo.value = RequestResult(success = userInfo)
                                _dialog.dismiss()
                            }
                            .show()

                        setEdiTextFocusPoint(builder)

                    }
                    else -> {
                    }
                }

            }
    }

    private fun setObservers() {
        userInfoViewModel.loadUserInfo()
        userInfoViewModel.userInfo.observe(this, { it ->
            it?.success?.let {
                with(it) {
                    Glide.with(this@UserInfoEditActivity)
                        .load(AppConstants.STATIC_SOURCE_URL + headImg)
                        .placeholder(R.mipmap.logo)
                        .error(R.drawable.error)
                        .into(head_image)

                    initUserInfo(this)
                }
            }

        })

        userInfoViewModel.saveState.observe(this, {
            it?.success?.let {
                userInfoViewModel.loadUserInfo()
                Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show()
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            RequestCode.SWITCH_HEAD_IMAGE -> {
                data?.data?.let {
                    hasSwitchHeadImage = true
                    head_image.setImageURI(it)
                }
            }
        }
    }

    private fun setEdiTextFocusPoint(builder: QMUIDialog.EditTextDialogBuilder) {
        val text = builder.editText.text
        if (text is Spannable) {
            Selection.setSelection(text, text.length)
        }
    }

    private fun bitmap2Bytes(bitmap: Bitmap): ByteArray {
        val bos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos)
        return bos.toByteArray()
    }

    private fun initUserInfo(user: LoggedInUser) {
        val dataList = mutableListOf<MutableMap<String, Any>>()
        for (i in attributes.indices) {
            dataList.add(
                mutableMapOf(
                    Pair(ATTRIBUTE, attributes[i]),
                    Pair(ACTION, R.drawable.more_gray)
                )
            )
            when (i) {
                UserInfo.NICK_NAME.ordinal -> {
                    user.userName?.let { dataList[i].put(VALUE, it) }
                }
                UserInfo.GENDER.ordinal -> {
                    user.sex?.let { dataList[i].put(VALUE, it) }
                }
                UserInfo.BIRTHDAY.ordinal -> {
                    user.birthDay?.let { dataList[i].put(VALUE, it) }
                }
                UserInfo.LIFE_STATUS.ordinal -> {
                    user.marry?.let { dataList[i].put(VALUE, it) }
                }
                UserInfo.JOB.ordinal -> {
                    user.major?.let { dataList[i].put(VALUE, it) }
                }
                UserInfo.HOBBY.ordinal -> {
                    user.hobbit?.let { dataList[i].put(VALUE, it) }
                }
                UserInfo.SIGN.ordinal -> {
                    user.sign?.let { dataList[i].put(VALUE, it) }
                }
                else -> continue
            }

        }

        user_info_list.adapter = SimpleAdapter(
            this, dataList, R.layout.item_user_info, arrayOf(
                ATTRIBUTE, VALUE, ACTION
            ), intArrayOf(R.id.attribute, R.id.value, R.id.icon)
        )

    }

    enum class UserInfo {
        NICK_NAME,
        GENDER,
        BIRTHDAY,
        LIFE_STATUS,
        JOB,
        HOBBY,
        SIGN
    }

    companion object {
        fun newInstance() = UserInfoEditActivity()
    }

}

